package server

import (
	"git.oschina.net/ant180/gotesser/pub"
	"git.oschina.net/ant180/gotesser/api"
	"github.com/xlvector/dlog"
	"regexp"
	"errors"
	"strings"
	"strconv"
)

type Tesser interface {
	Recognize(tesser *api.Tesser, data []byte, lang string, psm string) (string, error)
}


type TesserHandleFunc func(*api.Tesser, []byte, string, string) (string, error)

func (p TesserHandleFunc) Recognize(tesser *api.Tesser, data []byte, lang, psm string) (string, error) {
	return p(tesser, data, lang, psm)
}



var tesserHandles = map[int]Tesser {
	pub.CAPTCHA_CODE_OPPO: &CaptchaOppo{},
	pub.CAPTCHA_CODE_SZCREDIT: &CaptchaSzc{regp:regexp.MustCompile("(\\d+)(.*?)(\\d+)")},
}

type CaptchaOppo struct {
}

func initParams(tesser *api.Tesser, lang, psm string) error {
	if len(lang) != 0 {
		tesser.SetLanguage(lang)
	}else{
		tesser.SetLanguage("eng")
	}
	//Notice: psm

	return tesser.Init()
}

func (p *CaptchaOppo) Recognize(tesser *api.Tesser, data []byte, lang, psm string) (string, error) {
	err := initParams(tesser, lang, psm)
	if err != nil {
		dlog.Error("oppo tesser init fail! %v", err)
		return "", err
	}
	rs, err := tesser.RecognizeMem(data)
	if err != nil {
		dlog.Error("oppo tesser recognize fail! %v", err)
		return "", err
	}

	return rs, nil
}

//深证企业信用信息
type CaptchaSzc struct {
	regp *regexp.Regexp
}

func (p *CaptchaSzc) Recognize(tesser *api.Tesser, data []byte, lang, psm string) (string, error) {
	err := initParams(tesser, lang, psm)
	if err != nil {
		dlog.Error("scz tesser init fail! %v", err)
		return "", err
	}
	rs, err := tesser.RecognizeMem(data)
	if err != nil {
		dlog.Error("scz tesser recognize fail! %v", err)
		return "", err
	}

	reprs := p.regp.FindStringSubmatch(rs)
	if len(reprs) <= 0 {
		dlog.Error("scz r! %v", err)
		return "", errors.New("sec regp fail!")
	}
	a,err := strconv.Atoi(reprs[1])
	if len(reprs) <= 0 {
		dlog.Error("scz r! %v", err)
		return "", errors.New("sec strconv fail!")
	}
	b,err := strconv.Atoi(reprs[3])
	if len(reprs) <= 0 {
		dlog.Error("scz r! %v", err)
		return "", errors.New("sec strconv fail!")

	}
	var ret string
	switch strings.TrimSpace(reprs[2]){
	case "加":
		ret = strconv.Itoa(a+b)

	case "减":
		ret = strconv.Itoa(a-b)
	case "乘":

		ret = strconv.Itoa(a*b)
	case "除":
		ret = strconv.Itoa(a/b)
	default:
		dlog.Error("scz r! %v", err)
		return "", errors.New("sec not + - * /!")
	}
	return ret, nil

}
